package com.blt.govdata.controller;

import com.baomidou.mybatisplus.MybatisSqlSessionTemplate;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * Description:分页查询前端控制器
 * Author:GongJun
 * Date:2018/3/27
 * Time:17:59
 * blt Technologies Co., Ltd.
 */
@RestController
@RequestMapping("/page")
public class PageSelectController {

    @Autowired
    MybatisSqlSessionTemplate template;

    //	@PostMapping(path = "/{serviceId}/{methodId}")
    public <T> Page<T> pageSelect(String serviceId, String methodId, @RequestBody Map<String, Object> params, @SessionAttribute String userId) {

        final Object pageNum = params.remove("pageNum");
        final Object pageSize = params.remove("pageSize");
        return this.pageSelect(serviceId, methodId, pageNum, pageSize, params, userId);
    }

    //	@PostMapping(path = "/{serviceId}/{methodId}/{pageNum}/{pageSize}")
    public <T> Page<T> pageSelect(String serviceId, String methodId, Object pageNum, Object pageSize, @RequestBody Map<String, Object> params,
                                  @SessionAttribute String userId) {

        final String id = serviceId.concat(".").concat(methodId);
        return this.function(pageNum, pageSize, p -> this.template.selectList(id, params, p));
    }

    private <T> Page<T> function(Object pageNum, Object pageSize, java.util.function.Function<Page<T>, List<T>> function) {

        int pn = (pageNum instanceof Integer) ? (Integer) pageNum : (pageNum instanceof String) ? Integer.parseInt(pageNum.toString()) : 0;
        int ps = (pageSize instanceof Integer) ? (Integer) pageSize : (pageSize instanceof String) ? Integer.parseInt(pageSize.toString()) : 10;

        final Page<T> page = new Page<>(pn, ps);
        page.setRecords(function.apply(page));
        return page;
    }
}
